"""data_reciever.py -- defines the UDPServer that recieves the monitor
data
"""

from SocketServer import UDPServer, BaseRequestHandler

from mon_session import getidbyip
import logging
#import mon_center_logger

logger = logging.getLogger('center.date_reciever')

class DRRequestHandler(BaseRequestHandler):

    def __init__(self, request, client_address, server, queue):
        self.queue = queue
        BaseRequestHandler.__init__(self, request, client_address, server)

    def handle(self):
        #logger.debug("recieved 1 msg from %s:%d" % \
        #             (self.client_address[0], self.client_address[1]))
        #print self.request
        data = [self.request[0], self.client_address]
        #print data
        data = self.mangle(data)
        logger.debug('msg from %s:%d - %s' % (data[1][0], data[1][1], data[0])) 
        self.queue.put(data, True)

    def mangle(self, data):
        # convert the host addr to its id
        nodeID = getidbyip(data[1][0])
        return [data[0], (nodeID, data[1][1])]

class DataReciever(UDPServer):

    def __init__(self, server_address, queue,\
                 RequestHandlerClass=DRRequestHandler,\
                 bind_and_activate=True):
        UDPServer.__init__(self, server_address, RequestHandlerClass)
        self.queue = queue

    def verify_request(self, request, client_address):
        # TODO check if host is on node list
        return True

    def finish_request(self, request, client_address):
        self.RequestHandlerClass(request, client_address, self, self.queue)

